package cn.itcast.take_delivery.web.action;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import cn.itcast.bos.domain.take_delivery.Promotion;
import cn.itcast.bos.web.action.BaseAction;
import cn.itcast.take_delivery.service.PromotionService;

@ParentPackage("json-default")
@Namespace("/")
@Scope("prototype")
@Action
public class PromotionAction extends BaseAction<Promotion>{
	
	private File titleImgFile;
	public void setTitleImgFile(File titleImgFile) {
		this.titleImgFile = titleImgFile;
	}
	private String titleImgFileFileName;
	public void setTitleImgFileFileName(String titleImgFileFileName) {
		this.titleImgFileFileName = titleImgFileFileName;
	}

	@Autowired
	private PromotionService promotionService;

	@Action(value="promotionSave",
			results={@Result(name="success",type="redirect",location="./pages/take_delivery/promotion.html")})
	public String save() throws IOException{
		String rootPath = ServletActionContext.getServletContext().getRealPath("/upload/");
		String rootUrl = ServletActionContext.getRequest().getContextPath()+"/upload/";
		
		UUID uuid = UUID.randomUUID();
		System.out.println(titleImgFileFileName);
		//切割
		String ext = titleImgFileFileName.substring(titleImgFileFileName.lastIndexOf("."));
		System.out.println(ext);
		String randomName=uuid+ext;//文件名
		File file = new File(rootPath+"/"+randomName);
		
		FileUtils.copyFile(titleImgFile, file);
		model.setTitleImg(ServletActionContext.getRequest().getContextPath()+"/upload/"+randomName);
		
		promotionService.save(model);
		
		return SUCCESS;
	}
	
	@Action(value="promotion_findByPage",results={@Result(name="success",type="json")})
	public String findByPage(){
		Pageable pageable = new PageRequest(page-1, rows);
		Page<Promotion> pageData = promotionService.findByPage(pageable);
		//压栈
		pushToValueStack(pageData);
		return SUCCESS;
	}
}
